// 螺旋矩阵
// https://leetcode.cn/problems/spiral-matrix/description/
/**
输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出：[1,2,3,6,9,8,7,4,5]
示例 2：


输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出：[1,2,3,4,8,12,11,10,9,5,6,7]

 */

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
    // 定义方向，顺时针方向
    const directions = [
        [0, 1],
        [1, 0],
        [0, -1],
        [-1, 0],
    ];
    let dirCur = 0;

    // 二维坐标
    let x = 0; // 行
    let y = 0; // 列

    // 点日志
    let pointLog = {};

    let ret = [matrix[x][y]];
    pointLog[`x${x}y${y}`] = 1;

    for (let i = 0; i < matrix.length * matrix[0].length - 1; i++) {
        let tempX = x + directions[dirCur][0];
        let tempY = y + directions[dirCur][1];

        if (
            pointLog[`x${tempX}y${tempY}`] != null ||
            tempX < 0 ||
            tempX >= matrix.length ||
            tempY < 0 ||
            tempY >= matrix[0].length
        ) {
            dirCur = dirCur + 1;
            if (dirCur >= 4) dirCur = 0;

            tempX = x + directions[dirCur][0];
            tempY = y + directions[dirCur][1];
        }

        x = tempX;
        y = tempY;
        ret.push(matrix[x][y]);
        pointLog[`x${x}y${y}`] = 1;
    }

    console.log(JSON.stringify(ret));
};

spiralOrder([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]);
spiralOrder([
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
]);
